<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import axios from 'axios'
import { showNotify } from 'vant';
import { useRouter } from 'vue-router'
import { setBg, bgColors, isPhone } from '@/plugins/util.js'
import { setUserExtInfoApi } from '@/plugins/http/api/user'

import draggable from "vuedraggable";
import { generateUUID, copyJSON, isNotEmpty, isEmpty, uploadFile } from '@/plugins/util.js'
import { showConfirmDialog } from 'vant';
import Pop from '@/components/pop/Pop.vue';

import { useConfirm } from '@/composition/useConfirm'

const { showConfirm, closeConfirm } = useConfirm();

// import { guides } from './homeData.js'


import { useUser } from '@/composition/useUser'
import { computed } from 'vue';

const { loginModel, user, login, loggedIn, logout } = useUser();

// const router = useRouter();

// let guides = computed(() => user.value.extInfo.guides);
let guides = ref(user.value.extInfo.guides);


/*
draggable 对CSS样式没有什么要求万物皆可拖拽
:list="state.list"         //需要绑定的数组
ghost-class="ghost"        //被替换元素的样式
chosen-class="chosenClass" //选中元素的样式
animation="300"            //动画效果
@start="onStart"           //拖拽开始的事件
@end="onEnd"               //拖拽结束的事件
*/

const guideSortChange = () => {
  for (let index = 0; index < guides.value.length; index++) {
    const item = guides.value[index];
    item.sort = index + 1;
    item.uuid = generateUUID();
  }
  user.value.extInfo.guides = guides.value;
  saveGuide2Db();
};

const show = ref(false);

const guideItem = ref({
  uuid: '',
  name: '',
  icon: '',
  url: '',
  urlZ: '',
  desc: '',
});


const saveGuide2Db = () => {
  if (loggedIn.value) {
    // save data to db
    let setUserExtInfoData = {
      appCode: 'F0FB4BED6B664CFEBBB30A688A4C8E3F',
      param: {
        userSet: user.value.extInfo
      }
    };
    setUserExtInfoApi(setUserExtInfoData).then(setUserExtInfoDataRes => {
      if (setUserExtInfoDataRes.code != '0') {
        showNotify({ type: 'danger', message: setUserExtInfoDataRes.message });
        return;
      }
      // showToast('保存设置成功');
      showNotify({ type: 'success', message: '保存设置成功' });
    })
  } else {
    showNotify({ type: 'success', message: '保存设置成功' });
  }
}


const guideSubmit = () => {
  if (isNotEmpty(guideItem.value.uuid)) {
    // 修改
    editGuide();
  } else {
    // 新增
    addGuide();
  }

}

const upIcon = async () => {
  if (!loggedIn.value) {
    return;
  }
  const icon = guideItem.value.icon;
  if (isNotEmpty(icon) && icon.startsWith('data:')) {
    // 上传到服务器，并且替换为url
    if (fileInfo != null) {
      const iconUrl = await uploadFile(fileInfo.file);
      console.log('iconUrl:', iconUrl);
      guideItem.value.icon = iconUrl;
      fileInfo = null;
    }
  }

}

const addGuide = async () => {
  // guideItem.value.sort = guides.value.length + 1;
  await upIcon();
  if (guideItem.value.icon == '') {
    guideItem.value.icon = 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=' + guideItem.value.name
  }
  guideItem.value.uuid = generateUUID();
  guides.value.push(copyJSON(guideItem.value));
  user.value.extInfo.guides = guides.value;
  show.value = false;
  saveGuide2Db();
}

const deleteGuide = (uuid) => {
  showConfirmDialog({
    title: '提示',
    message: '确认删除吗？',
  }).then(() => {
    // on confirm
    guides.value = guides.value.filter(item => item.uuid != uuid);
    user.value.extInfo.guides = guides.value;
    saveGuide2Db();
  }).catch(() => {
    // on cancel
  });
}

const showAddGuide = () => {
  show.value = true;
  guideItem.value = {};
  fileList.value = [];
}

const showEditGuide = (guide) => {
  // user.value.extInfo.guides = guides.value;
  // saveGuide2Db();
  // debugger;
  show.value = true;
  guideItem.value = copyJSON(guide);
  fileList.value = [];
  fileList.value.push(
    {
      url: guideItem.value.icon,
      isImage: true
    }
  );
}

const editGuide = async () => {
  await upIcon();
  // debugger;
  guides.value.forEach(item => {
    if (item.uuid == guideItem.value.uuid) {
      item.name = guideItem.value.name;
      item.url = guideItem.value.url;
      item.icon = guideItem.value.icon;
      return false;
    }
  });
  user.value.extInfo.guides = guides.value;
  show.value = false;
  saveGuide2Db();
}

const guideForm = ref();

const guideConfirm = () => {
  show.value = false;
  // const validationStatus = guideForm.value.getValidationStatus();
  // console.log(validationStatus);
  // guideForm.value.submit();
  // return false;
}


const fileList = ref([
  // {
  //   url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg',
  //   isImage: true
  // }
]);
let fileInfo = null;
const afterRead = (file, detail) => {
  // start upload
  fileInfo = file;
  // console.log(fileInfo);
  // const fileReader = new FileReader();
  // fileReader.readAsDataURL(file.file);
  // fileReader.onload = () => {
  //   console.log(fileReader.result);
  //   guideItem.value.icon = fileReader.result;
  // }

  guideItem.value.icon = fileInfo.content;

  // console.log(fileList);
  // fileList.value = [];
  // fileList.value.push(
  //   {
  //     url: guideItem.value.icon,
  //     isImage: true
  //   }
  // );
  // uploadFile(fileInfo.file);
}


const getDefaultIcon = () => {
  const name = guideItem.value.name;
  const icon = guideItem.value.icon;
  if (isNotEmpty(name) && isEmpty(icon)) {
    guideItem.value.icon = 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=' + name;
  }
  fileList.value = [];
  fileList.value.push(
    {
      url: guideItem.value.icon,
      isImage: true
    }
  );
}

const delImg = () => {
  guideItem.value.icon = '';
  getDefaultIcon();
}


const popShow = ref(true);

</script>

<template>
  <!-- <Pop :show="popShow" @close="popShow = false"></Pop> -->
  <!-- :animation="300" -->
  <draggable class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-5 " v-model="guides"
    @change="guideSortChange" item-key="guides" filter=".opertion">
    <template #item="{ element }">
      <div class="shadow-md bg-white opacity-80">
        <div>
          <div class="w-full h-56 bg-cover bg-center bg-no-repeat flex items-end cursor-pointer rounded relative" :style="{
            backgroundImage: 'url(' + element.icon + ')'
          }">
            <div class="text-white w-full p-2 text-sm bg-black bg-opacity-20 truncate" :title="element.name">
              {{ element.name }}
            </div>
          </div>
          <div class="h-12 w-full flex justify-end items-center pr-2 space-x-3">
            <button type="button" @click="showEditGuide(element)" class="btn btn-primary">
              编辑
            </button>
            <button type="button" @click="deleteGuide(element.uuid)" class="btn btn-warning">
              删除
            </button>
          </div>
        </div>
      </div>
    </template>

    <template #footer>
      <div class="guide-footer" @click="showAddGuide()">
        <van-icon name="plus" />
      </div>
    </template>

  </draggable>

  <van-action-sheet v-model:show="show" title="导航">
    <van-form @submit="guideSubmit">
      <van-cell-group inset>
        <van-field v-model="guideItem.name" name="name" label="名称" placeholder="名称"
          :rules="[{ required: true, message: '请填写名称' }]" @blur="getDefaultIcon()" />
        <van-field v-model="guideItem.url" name="url" label="地址" placeholder="地址"
          :rules="[{ required: true, message: '请填写地址' }]" />
        <van-field name="uploader" label="图标">
          <template #input>
            <van-uploader v-model="fileList" :after-read="afterRead" reupload max-count="1" @delete="delImg" />
          </template>
        </van-field>
      </van-cell-group>
      <div style="padding: 0 2px;">
        <van-button block type="primary" native-type="submit">确定</van-button>
      </div>
    </van-form>
  </van-action-sheet>
</template>

<style scoped>
.guides {
  width: 100%;
}

.guide {
  padding: 10px;
  margin: 10px;
  background: rgb(0, 0, 0, 0.6);
  box-shadow: 0 0 1px 1px #999;
  border-radius: 5px;
  color: white;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.guide-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.guide-name {
  max-width: 60vw;
  margin-left: 10px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  /* word-break: keep-all; */
}

.guide-footer {
  cursor: pointer;
  padding: 15px;
  margin: 10px;
  background: rgb(0, 0, 0, 0.6);
  box-shadow: 0 0 1px 1px #999;
  border-radius: 5px;
  color: white;

  display: flex;
  justify-content: center;
  align-items: center;
}

.opertion {
  display: flex;
  justify-content: space-between;
}

.operationBtns {
  margin: 0 auto;
  width: 100%;
  text-align: center;
}

/* :deep(.van-grid-item) {
  width: 100%;
} */
</style>
